<template>
    <div ref="SmallDar" class="wh-100"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import chart from './SmallChart.js'

var _chart = null;

const props = defineProps({
    data: Object,
    type: String,
    color: Array,
})
const SmallDar = ref();

// 格式化数据方法
const buildChart = (res) => {
    // 哪怕 res.length 值为 0 ，只会不渲染数据，并不会阻止程序运行
    // 深拷贝位置更改
    let data = JSON.parse(JSON.stringify(res));
    var xAxisData = [];
    var SeriesData = [];
    for (var i = 0; i < data.length; i++) {
        xAxisData.push(data[i].name)
        SeriesData.push(data[i].value)
    }
    _chart.setData(xAxisData, SeriesData);
}

// 监听数据变化
watch(() => props.data, (res) => {
    buildChart(res);
})

// 初始化图表
onMounted(() => {
    _chart = new chart(SmallDar.value, {
        Grid: {
            top: 15,
            left: 30,
            right: 8,
            bottom: 25
        },
        type: props.type,
        Color: props.color,
    });
    buildChart(props.data);
})

// 组件注销时，删除图表
onUnmounted(() => {
    _chart.destroy()
})

</script>
<style scoped>
.wh-100 {
    width: 100%;
    height: 100%;
}
</style>